package org.example.security.interceptor;

import cn.hutool.core.util.StrUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.example.core.constant.TokenConstants;
import org.example.security.handler.SecurityHandler;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;

/**
 * @author 小杰_cc
 * @version 1.0
 */
public class BackendInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String refresh = request.getHeader(TokenConstants.REFRESH_MARK);
        if (StrUtil.isNotBlank(refresh)){
            response.setHeader(TokenConstants.REFRESH_MARK,refresh);
            response.addHeader("Access-Control-Expose-Headers",TokenConstants.REFRESH_MARK);
        }

        HashMap<String, String> map = new HashMap<>();
        map.put(TokenConstants.USER_ID,request.getHeader(TokenConstants.USER_ID));
        map.put(TokenConstants.USER_NAME,request.getHeader(TokenConstants.USER_NAME));
        SecurityHandler.setData(map);

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        SecurityHandler.remove();
    }
}
